package be.js.sqlCodeGenerator;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * An implementation of the SQLTemplate class
 * that generates triggers for auditing purposes.
 * 
 * $Id: AuditTrigger.java 81 2013-03-12 21:15:39Z johan.schamp@gmail.com $ 
 * @author johan schamp (johan.schamp@gmail.com)
 * 
 */
public class AuditTrigger extends SQLTemplate {

	/**
	 * Constructor. Calls the constructor of the parent.
	 * 
	 * @param templateName  an SQL template file name that is present in the 'templates' folder
	 * @param tableName a table name
	 * @param columns a list of columns for the table
	 * @param generatedFilePrefix a prefix for the generated files in the 'generated' folder
	 * @throws IOException
	 */
	public AuditTrigger(String templateName, String tableName, List<String> columns, String generatedFilePrefix) throws IOException{
		super(templateName, tableName, columns, generatedFilePrefix);
	}
	
	/**
	 * Generates auditing trigger code based on table name/ columns and the SQLtemplate.
	 * Input data is stored in templateSQL.
	 * After code generation, output data is available in generatedSQL field.
	 * 
	 */
	public void generate() throws IOException {
        HashMap<String, String> replacements = new HashMap<String, String>();
        replacements.put("tableName", tableName);
		
        // replace variables
        replaceVariables(replacements);
        
        // get string between loop
        String l = getBetweenVariable("loop");
        String result = "";

        // make replacements for column related lines
        for (int i = 0; i < columns.size(); i++ ){
            // new replacements map
            replacements = new HashMap<String, String>();
            replacements.put("columnName", columns.get(i));       
            result += replaceVariables(l, replacements);
			if (preserveCRLF){
				result  += SQLCodeGenerator.CRLF;
			}
        }        
        replaceBetweenVariable("loop", result);
        
        // save the sql
        saveGeneratedSQL(SQLCodeGenerator.GENERATEDDIR + "/" + generatedFilePrefix + tableName + SQLCodeGenerator.GENERATEDSUFFIX);
	}
}
